package com.zp.self.module.工具.json转换.jsonUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author ：by peng.zeng
 * @date ：Created 2022/1/17 13:48
 * @description ：用户json的合并
 */
public class JsonUtil {

    /**
     * Description: 读取文件为json对象
     */
    public static JSONArray getJson(String inPath2) throws IOException {
//        String str = FileUtils.readFileToString(file, "UTF-8");
//        maps = (List) JSONArray.fromObject(str);
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(inPath2));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "utf-8"), 5 * 1024 * 1024);// 用5M的缓冲读取文本文件
        JSONTokener jsonTokener = new JSONTokener(reader);
        JSONArray objects = new JSONArray(jsonTokener);
        fis.close();
        reader.close();
        return objects;
    }

    /**
     * Description: 导出json对象
     * @param jsonArray 目标array
     * @param outPathStr 导出路径
     */
    public static void writeJson( JSONArray jsonArray ,String outPathStr) throws IOException {
        // 将格式化后的字符串写入文件
        Writer write = new OutputStreamWriter(new FileOutputStream(outPathStr), "UTF-8");
        write.write( jsonArray.toString());
        write.flush();
        write.close();
    }

    /**
     * Description: json转化为csv
     * @param jsonArray  需要转化的json数组
     * @param outPathStr 需要导出的文件地址
     */
    public  static  void  json2csv( JSONArray jsonArray, String outPathStr) throws IOException {
        File file = new File(outPathStr);
//        JSONObject jo = mainJson.getJSONObject(0);
//        jo.put("optHours",0);
//        if(csvDemo!=null){
//            FileUtils.writeStringToFile(file, csvDemo, Charset.defaultCharset(), true);
//            JSONObject jo = jsonArray.optJSONObject(0);
//            JSONArray names = jo.names();
//            String csv = CDL.toString(names, jsonArray);
//            FileUtils.writeStringToFile(file, csv, "utf-8", true);
//        }else{
            String csv = CDL.toString(jsonArray);
            FileUtils.writeStringToFile(file, csv, "utf-8", true);
//        }

    }

    public static void multipleJsonMerge(JSONArray mainJson, JSONArray otherJson_0, String joinString, String... fields) {
        multipleJsonMerge(mainJson,otherJson_0,joinString,fields,new HashSet<>());
    }
    /**
     * Description: 将其他json数据的熟悉融合到主json中
     * @param mainJson    主json
     * @param otherJson_0 其他列json
     * @param joinString 关联属性
     * @param fields 属性
     * @param ForceStringFields 强制将值转换为字符串的属性
     */
    public static void multipleJsonMerge(JSONArray mainJson, JSONArray otherJson_0, String joinString, String[] fields,
                                         Set<String> ForceStringFields) {
        //循环为mainJson 添加字段
        for (String field : fields) {
            //1.将otherJson_0 的fields转换为map
            Map<String, String> otherJson_Map = new HashMap<>();
            int length = otherJson_0.length();
            for (int i = 0; i < length; i++) {
                Map<String, Object> otherJsondata = otherJson_0.getJSONObject(i).toMap();
                String joinId = otherJsondata.getOrDefault(joinString, "").toString();
                if (joinId != null && otherJsondata.get(field) != null) {
                    String value = otherJsondata.getOrDefault(field, "").toString();
                    otherJson_Map.put(joinId, value);
                }
            }
            //2.将当前字段field，加入到mainJson
            int mainLength = mainJson.length();
            for (int i = 0; i < mainLength; i++) {
                JSONObject jsonObject = mainJson.getJSONObject(i);
                Map<String, Object> mainJsondata = jsonObject.toMap();
                String joinId = mainJsondata.getOrDefault(joinString, "").toString();
                if (joinId != null ) {
                    if(ForceStringFields.contains(field))
                        jsonObject.put(field, "\t"+otherJson_Map.get(joinId)+"\t");
                    else
                        jsonObject.put(field, otherJson_Map.get(joinId));
                }
            }
        }
    }

    static ObjectMapper mapper = new ObjectMapper();
    static{
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    }

    /**
     * Description: 对象转json
     * @param o
     * @return java.lang.String
     */
    public static String toJsonStr(Object o){
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
